import Toast from 'tdesign-miniprogram/toast/index';
const app = getApp();
Page({
	toast(option) {
		Toast({
			context: this,
			selector: '#t-toast',
			...option,
		});
	},
	/**
	 * 页面的初始数据
	 */
	data: {
		nameValue: '',
		type: 1,
		phoneError: false,
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		const {
			value,
			type
		} = options;
		this.setData({
			nameValue: value,
			type
		});
	},
	clearContent() {
		this.setData({
			nameValue: '',
		});
	},

	/**
	 * 输入手机号检测手机号是否正确
	 * @param {*} e 
	 */
	onPhoneInput(e) {
		const { phoneError } = this.data;
		const isPhoneNumber = /^[1][3,4,5,7,8,9][0-9]{9}$/.test(e.detail.value);
		if (phoneError === isPhoneNumber) {
			this.setData({
				phoneError: !isPhoneNumber,
			});
		}
	},

	/**
	 * 提交表单
	 * @param {*} e 获取表单数据
	 */
	formSubmit(e) {
		let params = {
			openid: wx.getStorageSync('openid')
		};
		if (this.data.type == 1) {
			if (!e.detail.value.inputValue) {
				return this.toast({
					message: '昵称不能为空',
					theme: 'fail',
				});
			}
			params.nickName = e.detail.value.inputValue;
			this.updateUser(params);
		} else if (this.data.type == 2) {
			if (!e.detail.value.inputValue) {
				return this.toast({
					message: '手机号不能为空',
					theme: 'fail',
				});
			}
			params.phonenumber = e.detail.value.inputValue;
			this.updateUser(params);
		}
	},

	updateUser(params) {
		// 保存用户信息
		app.httpPost(`mini/user/update`, params).then((res) => {
			this.toast({
				message: res.message,
				theme: 'success',
			});
			// 回到上一个页面。。调用刷新，否则无法更新用户数据
			wx.navigateBack({
			  delta: 1,
			});
		});
	}
})